library(foreign)
library(ggplot2)
library(dplyr)
library(plyr)
library(reshape2)
library(imputeTS)

rm(list=ls())

data <- read.dta("./data/la_turnout_basic.dta")
data <- data[order(data$parish, data$year),]

###################################################################### 
# Figure 2 - Registration Rates by Understanding Clause
###################################################################### 

# Trim the Data
data_und <- data %>% filter(between(year, 1950, 1970))

# Impute Missing TS Values  
data_und <- ddply(data_und, .(parishnumber), transform, 
				brrate = na_ma(blackregrate, k=2),
				wrrate = na_ma(whiteregrate, k=2))

detach(package:plyr)

### Blacks
la_data <- data_und %>% group_by(year, understandingclause2) %>%
	summarize(mean_black = mean(brrate))
	 
# Reshape the Data
la_data2 <- melt(la_data, id.vars = c("understandingclause2","year"))
la_data2

la_data2$plotf <- ordered(la_data2$understandingclause2, levels = c(0,1),
				labels = c("Control", "Treated"))
			
ggplot(la_data2, aes(x=year, y=value, group=plotf)) + 
  geom_line(aes(colour=plotf)) + 
  geom_point(aes(shape=plotf), size=3) + 
  xlab("Year") + 
  ylab("Black Registration Rate") +
  theme_bw() +
  theme(legend.title=element_blank())


### Whites
la_data <- data_und %>%
	group_by(year, understandingclause2) %>%
	summarize(mean_white = mean(wrrate))
	 
# Reshape the Data
la_data2 <- melt(la_data, id.vars = c("understandingclause2","year"))
la_data2

la_data2$plotf <- ordered(la_data2$understandingclause, levels = c(0,1),
				labels = c("Control", "Treated"))
	
ggplot(la_data2, aes(x=year, y=value, group=plotf)) + 
  geom_line(aes(colour=plotf)) + 
  geom_point(aes(shape=plotf), size=3) + 
  xlab("Year") + 
  ylab("White Registration Rate") +
  theme_bw() +
  theme(legend.title=element_blank())

	 
